package com.grant.code.controller;

import java.io.File;
import java.io.IOException;
import java.nio.file.AccessDeniedException;
import java.time.LocalTime;
import java.util.Optional;

import com.grant.code.Main;
import com.grant.code.pojo.User;
import com.grant.code.service.UserService;
import com.grant.code.utils.DialogUtils;
import javafx.application.Platform;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.shape.Circle;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.nio.file.*;

import javafx.scene.control.Alert;
import javafx.scene.effect.DropShadow;
import javafx.scene.paint.Color;

/**
 * 用户管理控制器 - 处理用户相关的所有功能
 * 包括用户信息显示、头像管理、用户切换和编辑等功能
 */
public class UserController {
    
    private UserService userService;
    private final ObjectProperty<User> currentUserProperty = new SimpleObjectProperty<>();
    private ContextMenu userMenu;
    
    // 路径常量
    private static final Path AVATAR_DIR = Paths.get("avatars");
    private static final String DEFAULT_AVATAR = "/images/default-avatar.png";
    
    // UI 组件
    @FXML private Label lblWelcome;
    @FXML private Label statusBar;
    @FXML private ImageView userAvatar;
    
    /**
     * 默认构造函数
     */
    public UserController() {
        // 用于JavaFX FXML注入
    }

    /**
     * 带参数的构造函数
     * @param userService 用户服务
     * @param lblWelcome 欢迎标签
     * @param userAvatar 用户头像
     * @param statusBar 状态栏
     */
    public UserController(UserService userService, Label lblWelcome, ImageView userAvatar, Label statusBar) {
        this.userService = userService;
        this.lblWelcome = lblWelcome;
        this.userAvatar = userAvatar;
        this.statusBar = statusBar;
        
        // 初始化
        setupUserMenu();
    }
    
    /**
     * 初始化用户控制器
     * @param userService 用户服务
     */
    public void initialize(UserService userService) {
        this.userService = userService;
        setupUserMenu();
    }
    
    /**
     * 设置当前用户
     * @param user 用户对象
     */
    public void setCurrentUser(User user) {
        if (user == null) {
            System.err.println("警告: 尝试设置空用户");
            return;
        }
        
        // 输出用户信息日志
        System.out.println("设置当前用户: ID=" + user.getUserId() + 
                          ", 名称=" + user.getUserName() + 
                          ", 头像路径=" + user.getUserAvatar());
                          
        // 检查头像路径
        if (user.getUserAvatar() == null || user.getUserAvatar().isEmpty()) {
            // 尝试查找默认位置的头像
            try {
                Integer userId = user.getUserId();
                String[] extensions = {"png", "jpg", "jpeg", "gif"};
                for (String ext : extensions) {
                    Path defaultPath = AVATAR_DIR.resolve(userId + "." + ext);
                    if (Files.exists(defaultPath)) {
                        System.out.println("找到用户头像: " + defaultPath);
                        user.setUserAvatar(defaultPath.toString());
                        
                        // 如果userService可用，更新数据库
                        if (userService != null) {
                            userService.updateUserAvatar(userId, defaultPath.toString());
                        }
                        break;
                    }
                }
            } catch (Exception e) {
                System.err.println("检查用户头像时出错: " + e.getMessage());
            }
        }
        
        currentUserProperty.set(user);
    }
    
    /**
     * 获取当前用户
     * @return 当前用户对象
     */
    public User getCurrentUser() {
        return currentUserProperty.get();
    }
    
    /**
     * 更新当前用户信息
     * @param newUser 新的用户信息
     */
    public void updateCurrentUser(User newUser) {
        setCurrentUser(newUser); // 这会自动触发绑定的UI更新
        loadUserAvatar(); // 强制刷新头像
    }
    
    /**
     * 获取用户属性
     * @return 用户对象属性
     */
    public ObjectProperty<User> currentUserProperty() {
        return currentUserProperty;
    }
    
    /**
     * 设置用户菜单
     */
    private void setupUserMenu() {
        userMenu = new ContextMenu();
        
        // 设置菜单项，添加图标
        MenuItem changeAvatarItem = new MenuItem("切换头像");
        changeAvatarItem.setOnAction(e -> handleChangeAvatar());
        changeAvatarItem.setStyle("-fx-font-size: 14px;");

        MenuItem switchUserItem = new MenuItem("切换用户");
        switchUserItem.setOnAction(e -> switchUser());
        switchUserItem.setStyle("-fx-font-size: 14px;");

        MenuItem editUserItem = new MenuItem("编辑用户信息");
        editUserItem.setOnAction(e -> showEditUserDialog());
        editUserItem.setStyle("-fx-font-size: 14px;");

        // 添加分隔符
        SeparatorMenuItem separator = new SeparatorMenuItem();
        
        // 美化菜单样式
        userMenu.getItems().addAll(changeAvatarItem, separator, editUserItem, switchUserItem);
        userMenu.setStyle("-fx-background-color: white; -fx-border-color: #dee2e6; -fx-border-radius: 4px; -fx-effect: dropshadow(gaussian, rgba(0,0,0,0.15), 10, 0, 0, 3);");
    }
    
    /**
     * 处理头像点击事件
     * @param event 鼠标事件
     */
    @FXML
    public void handleAvatarClick(MouseEvent event) {
        javafx.geometry.Bounds bounds = userAvatar.localToScreen(userAvatar.getBoundsInLocal());
        userMenu.show(userAvatar, bounds.getMinX(), bounds.getMaxY() + 5);
    }
    
    /**
     * 处理更改头像的操作
     */
    public void handleChangeAvatar() {
        try {
            // 检查userService是否为null
            if (userService == null) {
                System.err.println("警告: userService为null，尝试从Spring上下文获取");
                // 使用Main类中的方法获取Spring上下文
                userService = Main.getContext().getBean(UserService.class);
                if (userService == null) {
                    showAlert(Alert.AlertType.ERROR, "错误", "无法获取用户服务", "请尝试重启应用");
                    return;
                }
            }

            // 创建文件选择器，允许用户选择图片文件
            FileChooser fileChooser = new FileChooser();
            fileChooser.setTitle("选择头像图片");
            fileChooser.getExtensionFilters().add(
                new FileChooser.ExtensionFilter("图片文件", "*.png", "*.jpg", "*.jpeg", "*.gif")
            );
            
            // 显示文件选择对话框
            File selectedFile = fileChooser.showOpenDialog(userAvatar.getScene().getWindow());
            if (selectedFile == null) {
                return; // 用户取消了选择
            }
            
            // 加载选择的图片
            try {
                Image originalImage = new Image(selectedFile.toURI().toString());
                
                // 加载裁剪对话框
                FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/AvatarCropperDialog.fxml"));
                DialogPane cropperPane = loader.load();
                
                // 获取裁剪器控制器
                AvatarCropperController cropperController = loader.getController();
                cropperController.setImage(originalImage);
                
                // 创建对话框
                Dialog<ButtonType> dialog = new Dialog<>();
                dialog.setDialogPane(cropperPane);
                dialog.setTitle("调整头像");
                dialog.initOwner(userAvatar.getScene().getWindow());
                
                // 显示对话框并等待结果
                Optional<ButtonType> result = dialog.showAndWait();
                
                // 处理对话框结果
                if (result.isPresent() && result.get() == ButtonType.OK) {
                    try {
                        // 获取裁剪后的图片文件
                        File croppedFile = cropperController.getCroppedImageFile();
                        
                        // 检查文件是否存在和可读
                        if (croppedFile == null || !croppedFile.exists() || !croppedFile.canRead()) {
                            throw new IOException("裁剪后的图像文件无效或无法访问");
                        }
                        
                        // 保存原始头像，以便在出错时恢复
                        Image oldAvatar = userAvatar.getImage();
                        
                        // 确保头像目录存在
                        Files.createDirectories(AVATAR_DIR);
                        
                        // 创建永久保存的头像文件
                        String extension = getFileExtension(croppedFile.getName());
                        String userId = String.valueOf(currentUserProperty.get().getUserId());
                        File permanentAvatarFile = new File(AVATAR_DIR.toFile(), userId + "." + extension);
                        
                        // 复制临时文件到永久文件
                        Files.copy(croppedFile.toPath(), permanentAvatarFile.toPath(), 
                                   StandardCopyOption.REPLACE_EXISTING);
                        
                        System.out.println("头像已保存到永久位置: " + permanentAvatarFile.getAbsolutePath());
                        
                        // 更新用户头像路径到数据库
                        userService.updateUserAvatar(currentUserProperty.get().getUserId(), 
                                                   permanentAvatarFile.getAbsolutePath());
                        
                        System.out.println("加载新头像: " + permanentAvatarFile.getAbsolutePath());
                        
                        // 清除缓存并加载新头像
                        Image newAvatar = new Image(permanentAvatarFile.toURI().toString(), 0, 0, true, true);
                        if (newAvatar.isError()) {
                            throw new IOException("新头像图像无效");
                        }
                        
                        // 打印图像大小信息
                        System.out.println("新头像图像大小: " + newAvatar.getWidth() + "x" + newAvatar.getHeight());
                        
                        // 更新UI
                        userAvatar.setImage(newAvatar);
                        applyAvatarStyle(userAvatar);
                        
                        // 确保头像点击事件
                        ensureAvatarClickHandler();
                        
                        // 更新状态
                        statusBar.setText("头像更新成功");
                        System.out.println("头像已成功更新: " + permanentAvatarFile.getAbsolutePath());
                    } catch (Exception e) {
                        e.printStackTrace();
                        statusBar.setText("头像更新失败: " + e.getMessage());
                        showAlert(Alert.AlertType.ERROR, "错误", "头像更新失败", "无法保存或加载新的头像: " + e.getMessage());
                    }
                }
            } catch (AccessDeniedException e) {
                statusBar.setText("访问被拒绝：" + e.getMessage());
                showAlert(Alert.AlertType.ERROR, "访问被拒绝", "无法访问所选文件", e.getMessage());
            } catch (IOException e) {
                statusBar.setText("读取文件出错：" + e.getMessage());
                showAlert(Alert.AlertType.ERROR, "文件读取错误", "无法读取所选文件", e.getMessage());
            } catch (Exception e) {
                e.printStackTrace();
                statusBar.setText("处理头像时出错：" + e.getMessage());
                showAlert(Alert.AlertType.ERROR, "处理错误", "处理头像时出错", e.getMessage());
            }
        } catch (Exception e) {
            e.printStackTrace();
            showAlert(Alert.AlertType.ERROR, "错误", "更改头像失败", e.getMessage());
        }
    }
    
    /**
     * 获取文件扩展名
     * @param filename 文件名
     * @return 扩展名
     */
    private String getFileExtension(String filename) {
        int lastDotIndex = filename.lastIndexOf(".");
        if (lastDotIndex > 0) {
            return filename.substring(lastDotIndex + 1);
        }
        return "png"; // 默认扩展名
    }
    
    /**
     * 应用头像样式 - 确保图像填充整个圆形区域
     * 
     * @param imageView 头像的ImageView
     */
    private void applyAvatarStyle(ImageView imageView) {
        try {
            if (imageView == null || imageView.getImage() == null) {
                return;
            }
            
            // 获取图像尺寸和 ImageView 尺寸
            double imgWidth = imageView.getImage().getWidth();
            double imgHeight = imageView.getImage().getHeight();
            double viewWidth = imageView.getFitWidth() > 0 ? imageView.getFitWidth() : imgWidth;
            double viewHeight = imageView.getFitHeight() > 0 ? imageView.getFitHeight() : imgHeight;
            
            // 计算圆形裁剪的半径 - 使用宽度的一半
            double radius = viewWidth / 2;
            
            // 设置圆形裁剪
            Circle clip = new Circle(radius, radius, radius);
            imageView.setClip(clip);
            
            // 设置保持宽高比并确保图片填满整个圆形区域
            imageView.setPreserveRatio(false);
            
            // 设置圆角效果（UI美化，非必须）
            imageView.setStyle("-fx-background-radius: " + radius + "px;");
            
            // 添加阴影效果
            DropShadow shadow = new DropShadow();
            shadow.setRadius(10.0);
            shadow.setOffsetX(0);
            shadow.setOffsetY(0);
            shadow.setColor(Color.color(0, 0, 0, 0.2));
            imageView.setEffect(shadow);
            
            // 确保能接收鼠标事件
            imageView.setPickOnBounds(true);
            imageView.setMouseTransparent(false);
        } catch (Exception e) {
            System.err.println("应用头像样式时出错: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    /**
     * 编辑用户信息
     */
    private void showEditUserDialog() {
        try {
            FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/EditUserDialog.fxml"));
            DialogPane dialogPane = loader.load();

            EditUserController controller = loader.getController();
            controller.initData(currentUserProperty.get());

            Dialog<ButtonType> dialog = new Dialog<>();
            dialog.setDialogPane(dialogPane);
            dialog.setTitle("编辑用户信息");
            dialog.initOwner(userAvatar.getScene().getWindow());

            // 添加关闭按钮类型
            dialog.getDialogPane().getButtonTypes().add(ButtonType.CLOSE);

            dialog.showAndWait().ifPresent(buttonType -> {
                if (buttonType == ButtonType.OK) {
                    User updatedUser = controller.getUpdatedUser();

                    new Thread(() -> {
                        userService.updateUser(updatedUser);
                        User freshUser = userService.getUserById(getCurrentUser().getUserId());

                        Platform.runLater(() -> {
                            setCurrentUser(freshUser); // 更新属性
                            statusBar.setText("用户信息更新成功！");
                        });
                    }).start();
                }
            });
        } catch (IOException e) {
            DialogUtils.showErrorDialog("错误", "加载失败: " + e.getMessage());
        }
    }
    
    /**
     * 切换用户
     */
    private void switchUser() {
        // 关闭当前窗口
        Stage currentStage = (Stage) userAvatar.getScene().getWindow();
        currentStage.close();

        // 重新显示登录界面
        try {
            Main.showLogin();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 确保头像点击事件处理器存在
     */
    private void ensureAvatarClickHandler() {
        // 移除所有现有的鼠标点击事件处理器
        userAvatar.setOnMouseClicked(null);
        
        // 添加新的事件处理器
        userAvatar.setOnMouseClicked(this::handleAvatarClick);
        
        // 确保可点击
        userAvatar.setMouseTransparent(false);
        userAvatar.setPickOnBounds(true);
    }
    
    /**
     * 加载用户头像
     */
    public void loadUserAvatar() {
        try {
            Image avatar = loadAvatarImage();
            userAvatar.setImage(avatar);
            applyAvatarStyle(userAvatar);
            // 确保头像点击事件可用
            ensureAvatarClickHandler();
        } catch (Exception e) {
            userAvatar.setImage(loadDefaultAvatar());
            applyAvatarStyle(userAvatar);
            // 确保头像点击事件可用
            ensureAvatarClickHandler();
        }
    }
    
    /**
     * 加载头像图片
     * @return 头像图片
     */
    private Image loadAvatarImage() {
        if (currentUserProperty.get() == null) {
            System.err.println("当前用户为空，无法加载头像");
            return loadDefaultAvatar();
        }
        
        String avatarPath = currentUserProperty.get().getUserAvatar();
        System.out.println("尝试加载头像: " + avatarPath);
        
        if (avatarPath != null && !avatarPath.isEmpty()) {
            try {
                // 检查文件是否存在
                Path path = Paths.get(avatarPath);
                if (!Files.exists(path)) {
                    System.err.println("头像文件不存在: " + avatarPath);
                    
                    // 尝试从默认位置加载
                    Integer userId = currentUserProperty.get().getUserId();
                    if (userId != null) {
                        // 尝试加载几种常见格式
                        String[] extensions = {"png", "jpg", "jpeg", "gif"};
                        for (String ext : extensions) {
                            Path defaultPath = AVATAR_DIR.resolve(userId + "." + ext);
                            if (Files.exists(defaultPath)) {
                                System.out.println("找到默认位置的头像: " + defaultPath);
                                // 更新用户头像路径
                                userService.updateUserAvatar(userId, defaultPath.toString());
                                // 使用带缓冲区的读取方式
                                try (InputStream is = Files.newInputStream(defaultPath);
                                     BufferedInputStream bis = new BufferedInputStream(is)) {
                                    return new Image(bis);
                                }
                            }
                        }
                    }
                    
                    return loadDefaultAvatar();
                }
                
                // 使用带缓冲区的读取方式，不使用缓存
                try (InputStream is = Files.newInputStream(path);
                     BufferedInputStream bis = new BufferedInputStream(is)) {
                    Image image = new Image(bis);
                    System.out.println("头像加载成功: " + avatarPath);
                    return image;
                }
            } catch (Exception e) {
                System.err.println("头像加载失败: " + e.getMessage());
                e.printStackTrace();
                return loadDefaultAvatar();
            }
        }
        System.out.println("使用默认头像，路径为空");
        return loadDefaultAvatar();
    }
    
    /**
     * 加载默认头像
     * @return 默认头像图片
     */
    private Image loadDefaultAvatar() {
        try (InputStream is = getClass().getResourceAsStream(DEFAULT_AVATAR)) {
            return new Image(is);
        } catch (Exception e) {
            throw new RuntimeException("默认头像加载失败", e);
        }
    }
    
    /**
     * 更新欢迎信息
     */
    public void updateWelcomeMessage() {
        String greeting = getTimeBasedGreeting();
        if (lblWelcome != null && currentUserProperty.get() != null) {
            lblWelcome.setText(String.format("%s，%s！", greeting, currentUserProperty.get().getUserName()));
        }
    }
    
    /**
     * 获取基于时间的问候语
     * @return 问候语
     */
    public String getTimeBasedGreeting() {
        int hour = LocalTime.now().getHour();
        if (hour < 6) return "夜深了";
        if (hour < 12) return "早上好";
        if (hour < 18) return "下午好";
        return "晚上好";
    }

    /**
     * 显示警告对话框
     */
    private void showAlert(Alert.AlertType alertType, String title, String header, String content) {
        Alert alert = new Alert(alertType);
        alert.setTitle(title);
        alert.setHeaderText(header);
        alert.setContentText(content);
        alert.showAndWait();
    }
} 